﻿using Microsoft.AspNetCore.SignalR;

namespace SignalR_WebApi.Hubs
{
    public class ChatHub : Hub
    {
        private static Dictionary<string, string> dicUsers = new Dictionary<string, string>();

        public override Task OnConnectedAsync()
        {
            var cid = Context.ConnectionId;
            var client = Clients.Client(cid);
            Console.WriteLine($"ID:{cid}已连接");
            Clients.All.SendAsync("ReceivePublicMessageLogin", $"{cid}加入了聊天室");
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var cid = Context.ConnectionId;
            var client = Clients.Client(cid);
            Console.WriteLine($"ID:{cid}已断开");
            Clients.All.SendAsync("ReceivePublicMessageLogin", $"{cid}离开了聊天室");
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendPublicMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceivePublicMessage", user, message);
        }

        /// <summary>
        /// 用户登录（不判断密码）
        /// </summary>
        /// <param name="userId"></param>
        public void Login(string userId)
        {
            if (!dicUsers.ContainsKey(userId))
            {
                dicUsers[userId] = Context.ConnectionId;
            }
            Console.WriteLine($"{userId}登录成功,ConnectionId={Context.ConnectionId}");
            //向当前所有用户发送当前在线的用户列表
            Clients.All.SendAsync("dicUsers",dicUsers.Keys.ToList());
        }

        public void ChatOne(string userId,string toUserId,string msg)
        {
            string newMsg = $"{userId}对你说{msg}";
            //如果当前用户在线
            if (dicUsers.ContainsKey(toUserId))
            {
                Clients.Client(dicUsers[toUserId]).SendAsync("ChatInfo",newMsg);
            }
            else
            {
                //如果用户不在线，正常是保存数据库，等上线时加载
            }
        }
    }
}